package concurrency;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 不正确地访问资源
 *
 * 2018年 09月 29日 星期六
 * @author fireway
 */
public class EvenChecker implements Runnable {
    private static final boolean DEBUG = true;

    private IntGenerator mIntGenerator;

    private int mId;

    public EvenChecker(IntGenerator intGenerator, int id) {
        mIntGenerator = intGenerator;
        mId = id;
    }

    @Override
    public void run() {
        while (!mIntGenerator.isCanceled()) {
            int value = mIntGenerator.next();
            if (value % 2 != 0) {
                System.out.println(value + " is not even!, which in " + Thread.currentThread() + ", id[" + mId + "]");
                // cancel all EvenChecker
                mIntGenerator.cancel();
            }
        }

        if (DEBUG) {
            System.out.println(Thread.currentThread() + ", id[" + mId + "]" + " is canceled");
        }
    }

    public static void test(IntGenerator intGenerator, int count) {
        System.out.println("Press Control-C to exit");
        ExecutorService exec = Executors.newCachedThreadPool();
        for (int i = 0; i < count; i++) {
            exec.execute(new EvenChecker(intGenerator, i));
        }
        exec.shutdown();
    }

    public static void test(IntGenerator intGenerator) {
        test(intGenerator, 10);
    }
}
